package net.vonkannen.callduration;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.telephony.TelephonyManager;

public class PhoneServiceReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		SharedPreferences settings = context.getSharedPreferences("CallDuration_prefs", 0);
	    boolean PhoneServiceReceiver = settings.getBoolean("PhoneServiceReceiver", true);

	    if(PhoneServiceReceiver) {
			String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
			
			if(state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
//				Log.i(context.getString(R.string.app_name), "Es wurde aufgelegt!");
				SharedPreferences.Editor editor = settings.edit();
				editor.putBoolean("newCall", false);
				editor.commit();
				
	            Intent pService = new Intent();
	            pService.setAction("net.vonkannen.callduration.CallDurationService");
	            
	            int sleep = 1000; // Waiting time before Log-database is accessed
	            PendingIntent piSync = PendingIntent.getService(context, 0, pService, 0);
//	            Log.i(context.getString(R.string.app_name), "schedulePendingSync: " + piSync.toString());
	            AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
	            alarm.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + sleep, piSync);
			}
	    }
	}

}
